package org.atlantis.ymer.command;

import org.atlantis.ymer.YmerException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ObjectNode;

@SuppressWarnings("unchecked")
public class PubCommand extends JsonCommand {

	private String topic;
	private Object message;
	private boolean isJson;

	public PubCommand(String topic, Object message) {
		this.topic = topic;
		this.message = message;
		this.isJson = message instanceof JsonNode;
	}

	public String getTopic() {
		return topic;
	}

	public <T> T getMessage(Class<T> messageType) {
		if (!isJson) return (T) message;

		JsonNode jsonMessage = (JsonNode) message;
		try {
			message = mapper.readValue(jsonMessage, messageType);
			isJson = false;
			return (T) message;
		} catch (Exception e) {
			throw new YmerException("Can not parse " + jsonMessage.toString() + " to " + messageType);
		}
	}

	@Override
	public CommandType getType() {
		return CommandType.PUB;
	}

	@Override
	protected JsonNode toJson() {
		ObjectNode node = mapper.createObjectNode();
		node.put("type", CommandType.PUB.getValue());
		ObjectNode dataNode = mapper.createObjectNode();
		dataNode.put("topic", topic);
		if (message instanceof String) dataNode.put("message", (String) message);
		else dataNode.putPOJO("message", message);
		node.put("data", dataNode);
		return node;
	}
}
